package com.paipaideli.ui.mine.safety;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jakewharton.rxbinding2.view.RxView;
import com.paipaideli.R;
import com.paipaideli.common.base.BasePresenterActivity;
import com.paipaideli.common.http.Api;
import com.paipaideli.common.pullrefresh.TStatusView;
import com.paipaideli.ui.home.adapter.SpaceItemDecoration;
import com.paipaideli.common.utils.ToastUtil;
import com.paipaideli.ui.mine.head.CashActivity;
import com.paipaideli.ui.mine.head.bean.BankBean;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by 我的银行卡
 */
public class MyBankActivity extends BasePresenterActivity {

    Unbinder unbinder;
    @BindView(R.id.top_back)
    RelativeLayout top_back;
    @BindView(R.id.top_title)
    TextView top_title;
    @BindView(R.id.bank_recycleview)
    RecyclerView bank_recycleview;
    @BindView(R.id.btn_bank_add)
    Button btn_bank_add;
    @BindView(R.id.bg_statusview)
    TStatusView bg_statusview;

    private BankAdapter bankAdapter;
    private List<BankBean.Data> list = new ArrayList<>();
    private int curPage = 1;
    private int total;

    private String which;

    @Override
    public int getContentView() {
        return R.layout.activity_mybank;
    }

    @Override
    public void initView() {
        unbinder = ButterKnife.bind(this);
        top_title.setText("我的银行卡");

        which = getIntent().getStringExtra("which");

        top_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        //添加银行卡
        RxView.clicks(btn_bank_add)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(o -> {
                    Intent intent = new Intent(MyBankActivity.this, ModifyBankActivity.class);
                    intent.putExtra("bank", "1");
                    startActivity(intent);
                }, throwable -> {
                });

        bankAdapter = new BankAdapter();
        bank_recycleview.setLayoutManager(new LinearLayoutManager(this));
        bank_recycleview.addItemDecoration(new SpaceItemDecoration(30));
        bank_recycleview.setAdapter(bankAdapter);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (list != null) {
            list.clear();
        }
        bg_statusview.showLoading();
        initDate();
    }

    public void initDate() {
        JSONObject requestData = new JSONObject();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().bank(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    if (request.code.equals("200")) {
                        list.addAll(request.data);
                        bankAdapter.notifyDataSetChanged();
                        bg_statusview.finish();
                        ToastUtil.show(request.msg);
                    } else {
                        bg_statusview.finish();
                        ToastUtil.show(request.msg);
                    }
                }, throwable -> {
                    bg_statusview.finish();
                    Log.e(TAG, "error", throwable);
                });
    }

    public void initDel(String id) {
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("id", id);
            requestData.put("isDel", 1);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().bankModify(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    if (request.getCode().equals("200")) {
                        finish();
                        bg_statusview.finish();
                        ToastUtil.show(request.getMessage());
                    } else {
                        bg_statusview.finish();
                        ToastUtil.show(request.getMessage());
                    }
                }, throwable -> {
                    bg_statusview.finish();
                    Log.e(TAG, "error", throwable);
                });
    }

    public class BankAdapter extends RecyclerView.Adapter {

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(MyBankActivity.this).inflate(R.layout.item_bank, null);
            inflate.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            return new ViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            ViewHolder viewHolder = (ViewHolder) holder;
            viewHolder.tvBankName.setText(list.get(position).bankName);
            viewHolder.tvBankNum.setText(list.get(position).bankNumber);
            viewHolder.tvBankType.setText(list.get(position).cardTypeName);

            RxView.clicks(viewHolder.btnDelete).subscribe(o -> {
                initDel(list.get(position).id);
                list.remove(position);//删除数据源,移除集合中当前下标的数据
                notifyItemRemoved(position);//刷新被删除的地方
                notifyItemRangeChanged(position, getItemCount()); //刷新被删除数据，以及其后面的数据
            }, throwable -> {
            });

            RxView.clicks(viewHolder.llItem).subscribe(o -> {
                if (which.equals("1")) {
                    Intent intent = new Intent(MyBankActivity.this, CashActivity.class);
                    intent.putExtra("bankName", list.get(position).bankName);
                    intent.putExtra("bankNum", list.get(position).bankNumber);
                    intent.putExtra("bankId", list.get(position).id);
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
                    Intent intent = new Intent(MyBankActivity.this, ModifyBankActivity.class);
                    intent.putExtra("bank", "2");
                    intent.putExtra("bankName", list.get(position).bankName);
                    intent.putExtra("bankNumber", list.get(position).bankNumber);
                    intent.putExtra("id", list.get(position).id);
                    intent.putExtra("cardTypeName", list.get(position).cardTypeName);
                    intent.putExtra("name", list.get(position).name);
                    intent.putExtra("phone", list.get(position).phone);
                    startActivity(intent);
                }
            }, throwable -> {
            });
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {

            @BindView(R.id.tv_bank_name)
            TextView tvBankName;
            @BindView(R.id.tv_bank_num)
            TextView tvBankNum;
            @BindView(R.id.tv_bank_type)
            TextView tvBankType;
            @BindView(R.id.ll_item)
            LinearLayout llItem;
            @BindView(R.id.btnDelete)
            Button btnDelete;
            @BindView(R.id.ll_delete)
            LinearLayout llDelete;

            public ViewHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
